package com.minidb.engine;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//存储引擎
public class StorageEngine {
    //每个表对应一个.dat文件，存储行数据
    private final String DATA_DIR = "data/";

    public StorageEngine(){
       File dir =new File(DATA_DIR);
       if (!dir.exists()){
           dir.mkdirs();
       }
    }

    //插入一行
    public void insert(String tableName, List<String> values) {
        try(FileWriter fw =new FileWriter(DATA_DIR +tableName +".dat" , true)){
            fw.write(String.join(",", values) +"\n");
        }catch (IOException e){
            throw new RuntimeException("插入失败：" + e.getMessage());
        }
    }

    //全盘扫描
    public List<List<String>> fullTableScan(String tableName){
        //TODO: 实现全盘扫描
        List<List<String>> rows =new ArrayList<>();
        try(BufferedReader br =new BufferedReader(new FileReader(DATA_DIR +tableName +".dat"))){
            String line;
            while ((line =br.readLine()) != null){
             rows.add(Arrays.asList(line.split(",")));
            }
        } catch (IOException e) {
            throw new RuntimeException("读取表数据失败：" + e.getMessage());
        }
        return rows;
    }
}
